<?php

namespace App\Repositories;

use App\Exceptions\GeneralException;
use App\Models\NetworkExpress;
use App\Models\Service;
use Illuminate\Support\Facades\Redis;

class ServiceRepository extends BaseRepository
{
    //服务站状态
    const SERVICE_STATUS = [
        1 => '运营中',
        2 => '已停业',
    ];

    //腾讯地图key
    const TENCENT_KEY = 'BWNBZ-P6OWD-U3K4L-PYHLY-E2FCO-UBFX5';

    /**
     *  REDIS_EXPIRES_FOR_HOUR 缓存有效期一小时
     */
    const REDIS_EXPIRES_FOR_HOUR = 3600;

    public function model()
    {
        return Service::class;
    }

    /**
     * 获取服务站列表
     *
     * @param $service_name
     * @param $limit
     * @param $owner_name
     * @param $status
     * @param $server_id
     * @param $admin_sign
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     * @throws GeneralException
     */
    public function getServices($service_name = false, $limit = false, $owner_name = false, $status = false, $server_id = false, $admin_sign = false)
    {
        $query = Service::query();
        if ($service_name !== false) {
            $query->where('designation', 'like', '%' . $service_name . '%');
        }
        if ($owner_name !== false) {
            $query->where('name', 'like', '%' . $owner_name . '%');
        }
        if ($server_id !== false) {
            $query->where(function ($query) use ($server_id) {
                $query->where('id', '=', $server_id)
                    ->orWhere('pid', '=', $server_id);
            });
        }
        if ($status !== false) {
            if (!array_key_exists($status, self::SERVICE_STATUS)) {
                throw new GeneralException('请选择正确站点的状态', 422);
            }
            $query->where('status', '=', $status);
        } else {
            if ($admin_sign === true) {
                $query->where('status', '=', 1);
            }
        }
        $services = $query
            ->withCount(["couriers", "networks", "childServices"])
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        return $services;
    }

    /**
     * 根据id获取服务站详情
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $service_id
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getServiceDetails($service_id)
    {
        $query = Service::query();
        $service = $query
            ->with(["couriers", "networks", "childServices", "province", "city", "district"])
            ->where('id', $service_id)
            ->first();
        return $service;
    }

    /**
     * 获取站点关联网点列表
     *
     * Date: 2018/06/14
     * @author Tenny
     * @param $service_id
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getRelationNetworks($service_id, $limit)
    {
        $query = NetworkExpress::query()
            ->with(["services", "network"])
            ->where('service_id', '=', $service_id);
        if ($limit !== false) {
            $service = $query->orderBy('created_at', 'desc')->paginate($limit);
        } else {
            $service = $query->get();
        }
        return $service;
    }

    /**
     * 获取服务站子站点列表
     * Date: 2018/06/14
     * @param $service_id
     * @param $limit
     * @author Tenny
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getChildServices($service_id = false, $limit = false)
    {
        $query = Service::query();
        if ($service_id !== false) {
            $query->where('pid', '=', $service_id);
        }
        $services = $query
            ->withCount(["childServices"])
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        return $services;
    }

    /**
     * 地图搜索功能
     * Date: 2018/06/15
     * @param $keyword
     * @param $region
     * @author Tenny
     * @return mixed
     * @throws GeneralException
     */
    public function search($keyword, $region = false)
    {
        $redis_key = sprintf('GET_ORDER_NUMBER_TEST_%s_%s', $keyword, $region);
        if (!Redis::exists($redis_key)) {
            $url = 'https://apis.map.qq.com/ws/place/v1/suggestion/?keyword=' . $keyword . '&key=' . self::TENCENT_KEY;
            if ($region !== false) {
                $url .= '&region=' . urlencode($region);
            }
            try {
                $ch = curl_init();
                $timeout = 5;   // 设置5秒超时
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                $file_contents = curl_exec($ch);
                curl_close($ch);
            } catch (\Illuminate\Database\QueryException $ex) {
                throw new GeneralException('未知错误', 500);
            }
            $res = json_decode($file_contents, true);
            if ($res !== null) {
                if (array_key_exists('status', $res) && $res['status'] == 0) {
                    Redis::setex($redis_key, self::REDIS_EXPIRES_FOR_HOUR, json_encode($res));
                } else {
                    $res = [];
                }
            } else {
                throw new GeneralException('未知错误', 500);
            }
        } else {
            $result = Redis::get($redis_key);
            $res = json_decode($result, true);
        }
        return $res;
    }

    /**
     * 获取主服务站列表
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getParentStation()
    {
        $query = Service::query();
        $services = $query
            ->where('is_child', '=', 0)
            ->where('status', '=', 1)
            ->orderBy('created_at', 'desc')
            ->get();
        return $services;
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}